UCI_DIR = fullfile("..", "UCI HAR Dataset");

[train_X, train_y] = process(UCI_DIR, "train");
[test_X, test_y] = process(UCI_DIR, "test");

train_y = uint8(train_y);
test_y = uint8(test_y);

train_X = train_X(train_y < 6, :, :);
train_y = train_y(train_y < 6);

test_X = test_X(test_y < 6, :, :);
test_y = test_y(test_y < 6);

save("UCIHAR_Train.mat", "train_X", "train_y");
save("UCIHAR_Test.mat", "test_X", "test_y");

function [X, y] = process(uci_dir, dir_name)
    directory = fullfile(uci_dir, dir_name);
    inertial_path = fullfile(directory, "Inertial Signals");

    ax = readtable(fullfile(inertial_path, strcat("body_acc_x_", dir_name, ".txt"))).Variables;
    ay = readtable(fullfile(inertial_path, strcat("body_acc_y_", dir_name, ".txt"))).Variables;
    az = readtable(fullfile(inertial_path, strcat("body_acc_z_", dir_name, ".txt"))).Variables;

    gx = readtable(fullfile(inertial_path, strcat("body_gyro_x_", dir_name, ".txt"))).Variables;
    gy = readtable(fullfile(inertial_path, strcat("body_gyro_y_", dir_name, ".txt"))).Variables;
    gz = readtable(fullfile(inertial_path, strcat("body_gyro_z_", dir_name, ".txt"))).Variables;

    X = zeros([size(ax), 6], "single");
    X(:,:,1) = ax;
    X(:,:,2) = ay;
    X(:,:,3) = az;
    X(:,:,4) = gx;
    X(:,:,5) = gy;
    X(:,:,6) = gz;

    y = readtable(fullfile(directory, strcat("y_", dir_name, ".txt"))).Variables;

end
